package com.example.hblog.interceptors;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.hblog.utils.JWTUtils;
import org.json.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin",origin);
        response.setHeader("Access-Control-Allow-Methods"," POST, GET,OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age","2592000");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild, token, HBlogToken");
        response.setHeader("Access-Control-Allow-Credentials","true");

        Map<String ,Object> map = new HashMap<>();

        try{
            String LoginToken = request.getHeader("HBlogToken");
            JWTUtils.verify(LoginToken);
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","无效签名！");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","token过期！");
        }catch(AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","token算法不一致！");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","token无效！");
        }
        map.put("state",false);
        return false;

    }
}
